# -*- coding: utf-8 -*-
# @Time    : 2021/10/21
# @Author  : CHENlj
# @File    : Email.py

"""
封装发送邮件的方法
"""
import smtplib, os, sys
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from Common.Log import Mylog
from Common.Compression import Compression
from Config.config import Config
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.append(BASE_DIR)


class Email:

    def __init__(self):
        self.compression = Compression()
        self.conf = Config()

    def send_email(self, msg_from, passwd, msg_to, subject, text_content, file_path):
        # msg_from = 'from@runoob.com'
        # msg_to = ['429240967@qq.com']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
        zippath = self.compression.toZip(file_path)
        if zippath:
            # 创建一个带附件的实例
            message = MIMEMultipart()
            message['From'] = Header(msg_from, 'utf-8')
            message['To'] = Header(msg_to, 'utf-8')
            message['Subject'] = Header(subject, 'utf-8')

            # 邮件正文内容
            message.attach(MIMEText(text_content, 'plain', 'utf-8'))

            # 构造附件
            att1 = MIMEText(open(zippath, 'rb').read(), 'base64', 'utf-8')
            att1["Content-Type"] = 'application/octet-stream'
            # 这里的filename可以任意写，写什么名字，邮件中显示什么名字
            att1["Content-Disposition"] = 'attachment; filename="report.zip"'
            message.attach(att1)
            smtp_obj = None
            try:
                smtp_obj = smtplib.SMTP_SSL(self.conf.host_mail, self.conf.port_mail)
                smtp_obj.login(msg_from, passwd)
                msg_to = msg_to.split(',')
                print(msg_to)
                # print(type(msg_to))
                smtp_obj.sendmail(msg_from, msg_to, message.as_string())
                print("邮件发送成功")
            except smtplib.SMTPException:
                print("Error: 请检查邮件的配置")
                Mylog.error("邮件发送失败，请检查邮件配置")

            finally:
                smtp_obj.quit()

        else:
            print("压缩文件为空")
            Mylog.error("压缩文件为空")


if __name__ == "__main__":

    email = Email()
    config = Config()
    email.send_email(config.sender_mail, config.password_mail, config.receiver_mail, config.subject_mail, config.content_mail, "./Report")